package com.strawcom.charmring.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import org.kymjs.kjframe.utils.DensityUtils;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.strawcom.charmring.App;
import com.strawcom.charmring.BaseActivity;
import com.strawcom.charmring.R;
import com.strawcom.charmring.util.LogUtil;
import com.strawcom.charmring.util.PingYinUtil;
import com.strawcom.charmring.view.MyLetterListView;
import com.strawcom.charmring.view.MyLetterListView.OnTouchingLetterChangedListener;
import com.strawcom.charmring.view.TitleView;

public class ContactActivity extends BaseActivity {

	private BaseAdapter adapter;
	private ListView listview;
	private TextView overlay;
	private MyLetterListView letterListView;
	private AsyncQueryHandler asyncQuery;
	private static final String NAME = "name", NUMBER = "number",
			SORT_KEY = "sort_key";
	private HashMap<String, Integer> alphaIndexer;
	private String[] sections;
	public List<ContentValues> list = new ArrayList<ContentValues>();
	private WindowManager windowManager;
	private TitleView titleView;
	private List<ContentValues> selectContacts = new ArrayList<ContentValues>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_contact);
		super.onCreate(savedInstanceState);

		initViews();
	}

	@SuppressWarnings("unchecked")
	private void initViews() {

		selectContacts = (List<ContentValues>) getIntent()
				.getSerializableExtra("list");

		windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());
		listview = (ListView) findViewById(R.id.list_view);
		letterListView = (MyLetterListView) findViewById(R.id.my_list_view);
		letterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());

		alphaIndexer = new HashMap<String, Integer>();
		titleView = (TitleView) findViewById(R.id.title_view);
		titleView.setTitleText(R.string.title_contact);
		
		TextView txNoData = (TextView)findViewById(R.id.tx_none_data);
		txNoData.setTypeface(App.i().tfYouYuan);
		
		initOverlay();
	}

	@Override
	public void onBackPressed() {
		Intent intent = getIntent();
		intent.putExtra("list", (Serializable) selectContacts);
		setResult(RESULT_OK, intent);
		finish();
	}

	@SuppressWarnings("deprecation")
	public void getContent() {
		Cursor cur = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		startManagingCursor(cur);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Uri uri = Uri.parse("content://com.android.contacts/data/phones");
		String[] projection = { "_id", "display_name", "data1", "sort_key" };
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				"sort_key COLLATE LOCALIZED asc");
	}

	private class MyAsyncQueryHandler extends AsyncQueryHandler {
		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

//			cursor.moveToFirst();

			while (cursor.moveToNext()) {
				ContentValues cv = new ContentValues();
				cv.put(NAME, cursor.getString(1));
				cv.put(NUMBER, cursor.getString(2));
				cv.put(SORT_KEY, PingYinUtil.getFirstSpell(cursor.getString(1)));
				list.add(cv);
			}
			
			if (list.size() > 0) {
				listview.setVisibility(View.VISIBLE);
				setAdapter(list);
			} else {
				listview.setVisibility(View.GONE);
			}
		}

	}

	private void setAdapter(List<ContentValues> list) {
		adapter = new ListAdapter(this, list);
		listview.setAdapter(adapter);

	}

	private class ListAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		private List<ContentValues> list;

		public ListAdapter(Context context, List<ContentValues> list) {
			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++) {
				String currentStr = getAlpha(list.get(i).getAsString(SORT_KEY));
				String previewStr = (i - 1) >= 0 ? getAlpha(list.get(i - 1)
						.getAsString(SORT_KEY)) : " ";
				if (!previewStr.equals(currentStr)) {
					String name = getAlpha(list.get(i).getAsString(SORT_KEY));
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_contact, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.number = (TextView) convertView
						.findViewById(R.id.number);
				holder.btnAdd = (Button) convertView.findViewById(R.id.btn_add);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			ContentValues cv = list.get(position);
			holder.name.setText(cv.getAsString(NAME));
			holder.number.setText(cv.getAsString(NUMBER));

			String currentStr = getAlpha(list.get(position).getAsString(
					SORT_KEY));
			String previewStr = (position - 1) >= 0 ? getAlpha(list.get(
					position - 1).getAsString(SORT_KEY)) : " ";

			if (!previewStr.equals(currentStr)) {
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			} else {
				holder.alpha.setVisibility(View.GONE);
			}

			boolean isAdded=false;
			for (ContentValues c : selectContacts) {
				if (c.getAsString(NAME).equals(
						list.get(position).getAsString(NAME))
						&& c.getAsString(NUMBER).equals(
								list.get(position).getAsString(NUMBER))) {
					isAdded=true;
					break;
				}
			}

			if (isAdded) {
				holder.btnAdd.setBackgroundResource(R.color.transparent);
				holder.btnAdd.setText(R.string.added);
				holder.btnAdd.setTextColor(getResources().getColor(
						R.color.done_text_color_normal));
			} else {
				holder.btnAdd
						.setBackgroundResource(R.drawable.selector_btn_blue_3);
				holder.btnAdd.setText(R.string.add);
				holder.btnAdd.setTextColor(getResources().getColor(
						R.color.white));
			}

			final int index = position;
			holder.btnAdd.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					if(selectContacts.contains(list.get(index))) {
						LogUtil.d("already added");
						return;
					}
					
					selectContacts.add(list.get(index));
					holder.btnAdd.setBackgroundResource(R.color.transparent);
					holder.btnAdd.setText(R.string.added);
					holder.btnAdd.setTextColor(getResources().getColor(
							R.color.done_text_color_normal));
				}
			});
			return convertView;
		}

		private class ViewHolder {
			TextView alpha;
			TextView name;
			TextView number;
			Button btnAdd;
		}
	}

	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.view_overlay, null);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				DensityUtils.dip2px(this, 120), DensityUtils.dip2px(this, 120),
				0, 0, WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		// WindowManager windowManager = (WindowManager)
		// this.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s, float y, float x) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);

				listview.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);

			}
		}

		@Override
		public void onTouchingLetterEnd() {
			overlay.setVisibility(View.GONE);
		}
	}

	private String getAlpha(String str) {
		if (str == null) {
			return "#";
		}

		if (str.trim().length() == 0) {
			return "#";
		}

		char c = str.trim().substring(0, 1).charAt(0);

		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase();
		} else {
			return "#";
		}
	}

	@Override
	protected void onDestroy() {
		if (windowManager != null) {
			windowManager.removeView(overlay);
		}
		super.onDestroy();
	}

}
